package scau.mis4.chanyulin.tools.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * Created by cyl on 2017/12/11.
 */
public class HttpUtils {

    /**
     * get请求，参数拼接在地址上
     * @param url 请求地址加参数
     * @return 响应
     */
    public static String httpGet(String url, int socketTimeout, int connectTimeout) throws IOException {
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig =
                RequestConfig.custom()
                        .setSocketTimeout(socketTimeout)
                        .setConnectTimeout(connectTimeout)
                        .build();
        HttpGet get = new HttpGet(url);
        get.setConfig(requestConfig);
        CloseableHttpResponse response;

        response = httpClient.execute(get);
        if (response != null && response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity);
        }
        if (response != null) response.close();
        httpClient.close();
        return result;
    }

}
